White's Studio.

LinCode - Backpack IIFollow

2018/08/24 Share

LinCode - Backpack IIFollow

Description

Given n items with size Ai and value Vi, and a backpack with size m. What’s the maximum value can you put into the backpack?

You cannot divide item into small pieces and the total size of items you choose should smaller or equal to m.

Have you met this question in a real interview? Yes

Problem Correction

Example

Given 4 items with size [2, 3, 5, 7] and value [1, 5, 2, 4], and a backpack with size 10. The maximum value is 9.

Analyst

  1. 最后一步

    F[n][m]表示前n个背包放入了重量mvalue

    最后一个背包A[n-1]能被放入: F[n][m] = F[n-1][m-A[n-1]] + B[n-1]

    最后一个背包A[n-1] 不能被放入:F[n][m] = F[n-1][m]

  2. 顺序:由小到大

  3. 边界情况:

    前0个放入任意重量 F[0][m] = Integer.MIN_VALUE

  4. 状态方程:

    F[n][m] = Math.max(F[n-1][m] ,F[n-1][m-A[n-1]] + B[n-1])

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
/**
* @param m: An integer m denotes the size of a backpack
* @param A: Given n items with size A[i]
* @param V: Given n items with value V[i]
* @return: The maximum value
*/
public int backPackII(int m, int[] A, int[] V) {
// write your code here
int len = A.length;
if (len == 0) return 0;

int[][] F = new int[len+1][m+1];

for (int i = 0; i <= m; i++)
F[0][i] = 0;

for (int i = 1; i <= len; i++) {
for (int j = 0; j <= m; j++) {
F[i][j] = F[i-1][j];
// for (int k = 0; k <= len; k++) {

// }

if (j >= A[i-1]) F[i][j] = Math.max(F[i-1][j], F[i-1][j - A[i-1]] + V[i-1]);
}
}

int result = Integer.MIN_VALUE;
for (int i = 0; i <= len; i++) {
result = Math.max(F[i][m], result);
}
return result;
}
}
CATALOG
  1. 1. LinCode - Backpack IIFollow
    1. 1.0.1. Description
    2. 1.0.2. Example
    3. 1.0.3. Analyst
    4. 1.0.4. Code